package com.wangshuo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.wangshuo.common.IpUtil;
import com.wangshuo.common.JwtHelper;
import com.wangshuo.common.MD5Util;
import com.wangshuo.common.RecordLoginLog;

import com.wangshuo.config.Result;

import com.wangshuo.config.ResultCodeEnum;
import com.wangshuo.domain.SysLoginLog;
import com.wangshuo.domain.SysUser;
import com.wangshuo.model.vo.LoginVo;
import com.wangshuo.service.SysLoginLogService;
import com.wangshuo.service.SysUserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.tomcat.util.net.IPv6Utils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/admin")
@Tag(name = "后台登录")
public class IndexController {
    @Resource
    private SysUserService service;
    @Resource
    private JwtHelper jwtHelper;
    @Resource
    private SysLoginLogService loginLogService;

    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo,HttpServletRequest request) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getUsername, loginVo.getUsername());
        SysUser sysUser = service.getOne(lambdaQueryWrapper);
        if (null == sysUser) {
            return Result.build(500, ResultCodeEnum.USERNAME_ERROR);
        }
        if (!MD5Util.encrypt(loginVo.getPassword()).equals(sysUser.getPassword())) {
            return Result.build(500, ResultCodeEnum.PASSWORD_ERROR);
        }
        if (sysUser.getStatus().intValue() == 0) {
            return Result.build(500, ResultCodeEnum.status_error);
        }
        System.out.println(sysUser.getId());
        RecordLoginLog recordLoginLog=new RecordLoginLog();
        recordLoginLog.recordLoginLog1(sysUser.getUsername(),1,IpUtil.getIpAddress(request),"登录成功");

        HashMap<String, Object> map = new HashMap<>();
        map.put("token", jwtHelper.createToken(sysUser.getId()));
        return Result.ok(map);
    }

    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
        Long uid=jwtHelper.getUserId(request.getHeader("token"));

        HashMap<String, Object> map = service.getUserInfo(uid);

        return Result.ok(map);

    }
@GetMapping("/loginrizhi")
public Result loginrizhi(){
    List<SysLoginLog> list=loginLogService.list();
    return Result.ok(list);
}
    @PostMapping("/logout")
    public Result logout() {
        return Result.ok("成功");
    }
}
